package com.cmhi.softmbh.util;

import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;

import com.cmhi.softmbh.MyApplication;
import com.cmhi.softmbh.cache.StaticConst;
import com.cmhi.softmbh.entity.Entity;
import com.cmhi.softmbh.provider.DBUtil;
import com.softmbh.kellyplatform.KellyPlatform;
import com.softmbh.kellyplatform.KellyUtils;
import com.softmbh.kellyplatform.bean.AppTokenBean;
import com.softmbh.kellyplatform.bean.AppTokenEnCryBean;
import com.softmbh.kellyplatform.bean.LicenseInfoBean;
import com.softmbh.kellyplatform.util.AppUtils;
import com.softmbh.kellyplatform.util.CheckerUtils;
import com.softmbh.kellyplatform.util.ChenDownQueue;
import com.softmbh.kellyplatform.util.GsonUtils;
import com.softmbh.kellyplatform.util.MacUtils;
import com.softmbh.kellyplatform.util.OkHttpUtil;
import com.softmbh.kellyplatform.util.encryptUtil.Base64Utils;
import com.softmbh.kellyplatform.util.encryptUtil.EncryptUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyAppUtils {


    public static String platToken = DBUtil.query(Entity.APP_TOKEN) == null ? "" : DBUtil.query(Entity.APP_TOKEN);

    public static boolean isRunBackground(Context mContext, String appPgName) {

        boolean isRunning = false;
        try {
            ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
            //100表示取的最大的任务数，info.topActivity表示当前正在运行的Activity，info.baseActivity表系统后台有此进程在运行
            for (ActivityManager.RunningTaskInfo info : list) {
                if (info.topActivity.getPackageName().equals(appPgName) || info.baseActivity.getPackageName().equals(appPgName)) {
                    isRunning = true;
                    break;
                }
            }
        } catch (Exception e) {
            isRunning = false;
        }
        return isRunning;
    }

    public static String getBaseInfo() {
        String info = MacUtils.getMac() + "," + DBUtil.query(Entity.VIRTUAL_MAC) + "," + MyApplication.appVersion + "," + StaticConst.CLIENT_MODE;
        AppUtils.debugLog("getBaseInfo: " + info);
        return Base64Utils.encode(info.getBytes(StandardCharsets.UTF_8));
    }


    public static void reportUserAction(String provinceCode, String action, String value, String extra, String extra2) {
        KellyUtils.getThreadPool().execute(() -> {
            String url = (StaticConst.KELLY_IS_TEST_SERVER ? "http://112.17.28.80:19091" : "https://softmbh.komect.com") + "/softmbh-app/v2/business/userAction";
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("action", action);
                jsonObject.put("value", value);
                if (!TextUtils.isEmpty(extra)) {
                    jsonObject.put("extra", extra);
                }

                if (!TextUtils.isEmpty(extra2)) {
                    jsonObject.put("extra2", extra2);
                }
            } catch (JSONException var9) {
                var9.printStackTrace();
            }
            String resultData = OkHttpUtil.init().post(url, jsonObject.toString(), provinceCode, getBaseInfo(), platToken);
            reportInfo("/softbox-app/v2/business/mobile/userAction", jsonObject.toString(), provinceCode, getBaseInfo());
            if (!TextUtils.isEmpty(resultData)) {
                try {
                    JSONObject jsonObject2 = new JSONObject(resultData);
                    int result = jsonObject2.optInt("code");
                    if (result == 0) {
                        AppUtils.Log("上报成功", "action:" + action);
                    } else {
                        String message = jsonObject2.optString("message");
                        AppUtils.Log("上报失败", "action:" + action + " message:" + message);
                    }
                } catch (JSONException var8) {
                    var8.printStackTrace();
                }
            } else {
                AppUtils.Log("同步用户操作失败", "返回数据为空 action:" + action + "  value:" + value);
            }
        });
    }


    public static void reportUserAction(String provinceCode, String action, String value, String extra, String extra2, CallBack<String> resultCallBack) {
        KellyUtils.getThreadPool().execute(() -> {
            String url = (StaticConst.KELLY_IS_TEST_SERVER ? "http://112.17.28.80:19091" : "https://softmbh.komect.com") + "/softmbh-app/v2/business/userAction";
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("action", action);
                jsonObject.put("value", value);
                if (!TextUtils.isEmpty(extra)) {
                    jsonObject.put("extra", extra);
                }

                if (!TextUtils.isEmpty(extra2)) {
                    jsonObject.put("extra2", extra2);
                }
            } catch (JSONException var9) {
                var9.printStackTrace();
            }

            String resultData = OkHttpUtil.init().post(url, jsonObject.toString(), provinceCode, getBaseInfo(), platToken);
            reportInfo("/softbox-app/v2/business/mobile/userAction", jsonObject.toString(), provinceCode, getBaseInfo());
            if (!TextUtils.isEmpty(resultData)) {
                try {
                    JSONObject jsonObject2 = new JSONObject(resultData);
                    int result = jsonObject2.optInt("code");
                    if (resultCallBack != null) {
                        if (result == 0) {
                            resultCallBack.onSuccess("上报成功");
                            AppUtils.Log("上报成功", "action:" + action);
                        } else {
                            String message = jsonObject2.optString("message");
                            AppUtils.Log("上报失败", "action:" + action + " message:" + message);
                            resultCallBack.onFail("上报失败", message, result);
                        }
                    }
                } catch (JSONException var8) {
                    var8.printStackTrace();
                }
            } else {
                AppUtils.Log("同步用户操作失败", "返回数据为空 action:" + action + "  value:" + value);
                if (resultCallBack != null) {
                    resultCallBack.onFail("上报失败", "返回数据为空", 10000);
                }
            }

        });
    }

    public interface CallBack<T> {
        void onSuccess(T var1);

        void onFail(String var1, String var2, int var3);
    }

    static void reportInfo(String url, String param, String provinceCode, String baseInfo) {
        if (!StaticConst.KELLY_IS_TEST_SERVER) {
            String temp = "https://mobile.sdbim.net:9096" + url;
            Request request = (new Request.Builder()).url(temp).addHeader("Content-Type", "application/json").addHeader("provinceCode", provinceCode).addHeader("baseInfo", baseInfo).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param)).build();
            AppUtils.debugLog("BIM", "url:" + temp + "  参数:" + param);

            try {
                ChenDownQueue.getOkhttpClient().newCall(request).enqueue(new Callback() {
                    public void onFailure(Call call, IOException e) {
                        AppUtils.debugLog("BIM", "onFailure:" + e.getLocalizedMessage());
                    }

                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
                            if (response.body() != null) {
                                AppUtils.debugLog("BIM", "success:" + response.body().string());
                            }
                        } else {
                            AppUtils.debugLog("BIM", "Response failure");
                            AppUtils.debugLog("BIM", "Response:" + GsonUtils.toJson(response));
                            AppUtils.debugLog("BIM", "ResponseBody:" + GsonUtils.toJson(response.body()));
                        }

                    }
                });
            } catch (Exception var7) {
                var7.printStackTrace();
                AppUtils.debugLog("BIM", "报错:" + var7.getLocalizedMessage());
            }
        }
    }


    public static void freshToken(String provinceCode) {
        String url = (StaticConst.KELLY_IS_TEST_SERVER ? "http://112.17.28.80:19091" : "https://softmbh.komect.com") + "/softmbh-app/v2/auth/getAppToken";
        JSONObject reqDataJson = new JSONObject();

        try {
            reqDataJson.put("vCode", "");
            reqDataJson.put("areaCode", provinceCode);
            reqDataJson.put("tvMac", MacUtils.getMac());
            String key = (String) CheckerUtils.clientKey.get(provinceCode);
            String reqdata = EncryptUtil.encryptStr(reqDataJson.toString(), key);
            JSONObject request = new JSONObject();
            request.put("clientId", provinceCode);
            request.put("reqData", reqdata);
            String resultData = OkHttpUtil.init().post(url, request.toString(), provinceCode, getBaseInfo());
            if (!TextUtils.isEmpty(resultData)) {
                AppTokenBean appTokenBean = (AppTokenBean) GsonUtils.jsonToBean(resultData, AppTokenBean.class);
                if (appTokenBean != null && appTokenBean.rspData != null) {
                    String rspData = EncryptUtil.decryptionStr(appTokenBean.rspData, key);
                    AppTokenEnCryBean appTokenEnCryBean = (AppTokenEnCryBean) GsonUtils.jsonToBean(rspData, AppTokenEnCryBean.class);
                    if (appTokenEnCryBean != null && appTokenEnCryBean.code == 0) {
                        platToken = appTokenEnCryBean.data.appToken;
                    }
                }
            } else {
                AppUtils.debugLog(" 刷新token 返回为空");
            }
        } catch (JSONException var10) {
            var10.printStackTrace();
        }

    }


    /**
     * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
     *
     * @param fieldName
     * @param value
     */
    public static void setFieldValue(String clz, String fieldName, Object value) {
        try {
            Class<?> bookClass = null;//完整类名
            bookClass = Class.forName(clz);
            Object object = bookClass.newInstance();//获得实例
            Field field = getDeclaredField(object, fieldName);
            if (field == null) {
                throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
            }
            makeAccessible(field);
            field.set(object, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredField
     *
     * @param object
     * @param filedName
     * @return
     */
    public static Field getDeclaredField(Object object, String filedName) {

        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredField(filedName);
            } catch (NoSuchFieldException e) {
                //Field 不在当前类定义, 继续向上转型
            }
        }
        return null;
    }

    /**
     * 使 filed 变为可访问
     *
     * @param field
     */
    public static void makeAccessible(Field field) {
        if (!Modifier.isPublic(field.getModifiers())) {
            field.setAccessible(true);
        }
    }
}
